﻿// ------------------------------------------------------------------------
//    XBMControl - A compact remote controller for XBMC (.NET 3.5)
//    Copyright (C) 2008  Bram van Oploo (bramvano@gmail.com)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// ------------------------------------------------------------------------

using System;
using System.Drawing;
using System.IO;

namespace XBMC
{
    public class XbmcControls
    {
        readonly XbmcCommunicator _parent;

        public XbmcControls(XbmcCommunicator p)
        {
            _parent = p;
        }

        public void SendVirtKey(char key)
        {
            var action = string.Format("0xF1{0:X}", (int)key);
            _parent.Request("SendKey", action);
        }

        public void SendBuiltInAction(char key)
        {
            var shift = 0x00020000;
            shift = shift + key;
            var action = string.Format("0x{0:X}", shift);
            _parent.Request("ExecBuiltIn", "Action(" + action + ")");
        }

        public void Play()
        {
            _parent.Request("ExecBuiltIn", "PlayerControl(Play)");
        }

        public void PlayAlbum(string albumId)
        {
            _parent.Controls.Stop();
            _parent.Controls.SendAction("10");
            _parent.Request("ClearPlayList(0)");
            _parent.Request("AddToPlayListFromDB(songs;idAlbum=" + albumId + ")");
            _parent.Request("SetCurrentPlaylist(0)");
            //_parent.Request("SetPlaylistSong(0)");
            _parent.Request("PlayNext");
        }

        public void PlayFile(string filename)
        {
            _parent.Request("PlayFile(" + filename + ")");
        }

        public void PlayMedia(string media)
        {
            _parent.Request("ExecBuiltIn", "PlayMedia(" + media + ")");
        }

        public void Stop()
        {
            _parent.Request("ExecBuiltIn", "PlayerControl(Stop)");
        }

        public void Next()
        {
            _parent.Request("ExecBuiltIn", "PlayerControl(Next)");
        }

        public void PlayListNext()
        {
            _parent.Request("PlayListNext");
        }

        public void Previous()
        {
            _parent.Request("ExecBuiltIn", "PlayerControl(Previous)");
        }

        public void ToggleShuffle()
        {
            _parent.Request("ExecBuiltIn", "PlayerControl(Random)");
        }

        public void PlayDrive()
        {
            _parent.Request("ExecBuiltIn", "PlayDVD");
        }


        public void EjectTray()
        {
            _parent.Request("ExecBuiltIn", "EjectTray()");
        }

        public void TogglePartymode()
        {
            _parent.Request("ExecBuiltIn", "PlayerControl(Partymode(music))");
        }

        public void Repeat(bool enable)
        {
            var mode = (enable) ? "Repeat" : "RepeatOff";
            _parent.Request("ExecBuiltIn", "PlayerControl(" + mode + ")");
        }

        public void LastFmLove()
        {
            _parent.Request("ExecBuiltIn", "LastFM.Love(false)");
        }

        public void LastFmHate()
        {
            _parent.Request("ExecBuiltIn", "LastFM.Ban(false)");
        }

        public void ToggleMute()
        {
            _parent.Request("ExecBuiltIn", "Mute");
        }

        public void SetVolume(int percentage)
        {
            _parent.Request("ExecBuiltIn", "SetVolume(" + Convert.ToString(percentage) + ")");
        }

        public void SeekPercentage(int percentage)
        {
            _parent.Request("SeekPercentage", Convert.ToString(percentage));
        }

        public void Reboot()
        {
            _parent.Request("ExecBuiltIn", "Reboot");
        }

        public void Shutdown()
        {
            _parent.Request("ExecBuiltIn", "Shutdown");
        }

        public void SendAction(string buttonAction)
        {
            _parent.Request("action", buttonAction);
        }

        public void Restart()
        {
            _parent.Request("ExecBuiltIn", "RestartApp");
        }

        public string GetGuiDescription(string field)
        {
            string returnValue = null;
            var aGuiDescription = _parent.Request("GetGUIDescription");

            foreach (var text in aGuiDescription)
            {
                var splitIndex = text.IndexOf(':') + 1;
                if (splitIndex <= 1) continue;
                var resultField = text.Substring(0, splitIndex - 1).Replace(" ", "").ToLower();
                if (resultField == field) returnValue = text.Substring(splitIndex, text.Length - splitIndex);
            }

            return returnValue;
        }

        public string GetScreenshotBase64()
        {
            var base64Screenshot = _parent.Request("takescreenshot", "screenshot.png;false;0;" + GetGuiDescription("width") + ";" + GetGuiDescription("height") + ";75;true;");
            return (base64Screenshot == null) ? null : base64Screenshot[0];
        }

        public static Image Base64StringToImage(string base64String)
        {
            Bitmap file = null;
            var bytes = Convert.FromBase64String(base64String);
            var stream = new MemoryStream(bytes);

            if (!string.IsNullOrEmpty(base64String))
                file = new Bitmap(Image.FromStream(stream));

            return file;
        }

        public Image GetScreenshot()
        {
            Image screenshot = null;
            var base64ImageString = GetScreenshotBase64();

            if (base64ImageString != null && !base64ImageString.Contains("Error"))
                screenshot = Base64StringToImage(base64ImageString);

            return screenshot;
        }

        public void UpdateLibrary(string library)
        {
            if(library == "music" || library == "video")
                _parent.Request("ExecBuiltIn", "updatelibrary(" + library + ")");
        }

    }
}
